<template>
  <el-config-provider :locale="zhCn">
    <div class="data-warehouse-container">
      <Sidebar 
        title="数据分类" 
        :items="sidebarItems" 
        :current-type="currentDataType"
        @select="handleTypeSelect"
      />

      <main class="data-main-content">
        <!-- Toolbar -->
        <div class="data-toolbar">
          <div class="search-box">
            <el-input 
              v-model="searchKeyword" 
              placeholder="请输入关键字，多个关键字以空格隔开" 
              clearable
              @keydown.enter="performSearch"
              style="width: 300px"
            >
              <template #append>
                <el-button @click="performSearch">
                  <el-icon><Search /></el-icon> 搜索
                </el-button>
              </template>
            </el-input>
          </div>
          
          <div class="toolbar-actions">
            <!-- 修改点：列设置下拉菜单 -->
            <el-popover
              placement="bottom"
              :width="200"
              trigger="click"
              popper-class="column-setting-popover"
            >
              <template #reference>
                <el-button>
                  <el-icon><Setting /></el-icon> 
                  <span style="margin: 0 4px">列设置</span>
                  <el-icon><ArrowDown /></el-icon>
                </el-button>
              </template>
              
              <!-- 下拉内容区域 -->
              <div class="column-settings-container">
                <!-- 全选控制区 -->
                <div class="column-settings-header">
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                  >
                    全选
                  </el-checkbox>
                </div>
                
                <!-- 列表滚动区 -->
                <div class="column-settings-list">
                  <div 
                    v-for="col in columnConfig" 
                    :key="col.key" 
                    class="column-setting-item"
                  >
                    <el-checkbox v-model="col.visible">
                      {{ col.label }}
                    </el-checkbox>
                  </div>
                </div>
              </div>
            </el-popover>

            <el-button type="danger" @click="handleClearData">
              <el-icon><Delete /></el-icon> 清空数据
            </el-button>
            <el-button type="warning" @click="handleDeleteData">
              <el-icon><Remove /></el-icon> 删除选中
            </el-button>
            <el-button type="success" @click="exportCurrentData">
              <el-icon><Download /></el-icon> 导出数据
            </el-button>
          </div>
        </div>

        <!-- Data Table -->
        <div class="data-table-wrapper" v-loading="loading">
          <el-table
            ref="tableRef"
            :data="pageData"
            style="width: 100%; height: 100%"
            border
            stripe
            height="100%"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
          >
            <el-table-column type="selection" width="55" align="center" fixed />
            <el-table-column type="index" label="序号" width="60" align="center" fixed />
            
            <template v-for="col in visibleColumns" :key="col.key">
              <el-table-column
                :prop="col.key"
                :label="col.label"
                :min-width="120"
                sortable="custom"
                show-overflow-tooltip
                class-name="draggable-column"
              >
                <template #default="scope">
                  {{ scope.row[col.key] }}
                </template>
              </el-table-column>
            </template>
            
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
        </div>

        <!-- Footer / Pagination -->
        <div class="data-footer">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 200, 500]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </main>
    </div>
  </el-config-provider>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, ElConfigProvider, ElPopover, ElCheckbox } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
// 修改点：增加 ArrowDown 图标引入
import { Search, Setting, Delete, Remove, Download, ArrowDown } from '@element-plus/icons-vue'
import Sortable from 'sortablejs'
import Sidebar from '@/components/Sidebar.vue'
import { fieldDict, fieldOrders, dataTypes, dataTypeIcons } from '@/utils/fields'
import { formatDate } from '@/utils'

const route = useRoute()

// State
const currentDataType = ref('bank')
const allData = ref([])
const filteredData = ref(null)
const searchKeyword = ref('')
const loading = ref(false)
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(50)
const columnConfig = ref([]) // { key, label, visible }
const tableRef = ref(null)
const sortState = ref({ prop: null, order: null })
let sortableInstance = null
const checkAll = ref(false)
const isIndeterminate = ref(false)

// Computed
const sidebarItems = computed(() => {
  return Object.keys(dataTypes).map(type => ({
    type,
    label: dataTypes[type],
    icon: dataTypeIcons[type]
  }))
})

const currentData = computed(() => {
  let data = filteredData.value || allData.value
  
  // Handle sorting
  if (sortState.value.prop && sortState.value.order) {
    data = [...data].sort((a, b) => {
      const valA = a[sortState.value.prop]
      const valB = b[sortState.value.prop]
      if (valA === valB) return 0
      const result = valA > valB ? 1 : -1
      return sortState.value.order === 'ascending' ? result : -result
    })
  }
  
  return data
})

const total = computed(() => currentData.value.length)

const pageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return currentData.value.slice(start, start + pageSize.value)
})

const visibleColumns = computed(() => {
  return columnConfig.value.filter(c => c.visible)
})

// Methods
const initColumns = () => {
  const keysSet = new Set()
  
  const defaultOrder = fieldOrders[currentDataType.value] || []
  defaultOrder.forEach(k => keysSet.add(k))
  
  if (allData.value.length > 0) {
    allData.value.forEach(row => {
      Object.keys(row).forEach(k => {
        if (k !== 'id' && k !== 'case_id' && k !== 'extra_data' && k !== 'row_hash' && k !== 'created_at' && k !== 'updated_at') {
          keysSet.add(k)
        }
      })
    })
  }
  
  const allKeys = Array.from(keysSet)
  
  const savedConfigKey = `columnConfig_${currentDataType.value}`
  const savedConfigStr = localStorage.getItem(savedConfigKey)
  let savedConfig = []
  try {
    savedConfig = savedConfigStr ? JSON.parse(savedConfigStr) : []
  } catch (e) {
    console.error('Failed to parse saved column config', e)
  }
  
  const newConfig = []
  
  savedConfig.forEach(savedCol => {
    if (allKeys.includes(savedCol.key)) {
      newConfig.push({
        key: savedCol.key,
        label: fieldDict[savedCol.key] || savedCol.key,
        visible: savedCol.visible
      })
      const index = allKeys.indexOf(savedCol.key)
      if (index > -1) allKeys.splice(index, 1)
    }
  })
  
  allKeys.forEach(key => {
    newConfig.push({
      key: key,
      label: fieldDict[key] || key,
      visible: true 
    })
  })
  
  columnConfig.value = newConfig
}

const saveColumnConfig = () => {
  const key = `columnConfig_${currentDataType.value}`
  localStorage.setItem(key, JSON.stringify(columnConfig.value))
}

const initSortable = () => {
  if (sortableInstance) sortableInstance.destroy()
  
  const el = tableRef.value?.$el.querySelector('.el-table__header-wrapper tr')
  if (!el) return

  sortableInstance = Sortable.create(el, {
    animation: 150,
    draggable: '.draggable-column',
    onEnd: (evt) => {
      const headerCells = Array.from(el.children)
      const firstDraggableIndex = headerCells.findIndex(cell => cell.classList.contains('draggable-column'))
      
      if (firstDraggableIndex === -1) return

      const oldIndex = evt.oldIndex - firstDraggableIndex
      const newIndex = evt.newIndex - firstDraggableIndex
      
      if (oldIndex < 0 || newIndex < 0) return
      
      const visibleCols = visibleColumns.value
      if (oldIndex >= visibleCols.length || newIndex >= visibleCols.length) return
      
      const movedItemKey = visibleCols[oldIndex].key
      
      const configOldIndex = columnConfig.value.findIndex(c => c.key === movedItemKey)
      const targetItemKey = visibleCols[newIndex].key
      const configTargetIndex = columnConfig.value.findIndex(c => c.key === targetItemKey)
      
      const item = columnConfig.value.splice(configOldIndex, 1)[0]
      columnConfig.value.splice(configTargetIndex, 0, item)
      
      saveColumnConfig()
    }
  })
}

const handleCheckAllChange = (val) => {
  columnConfig.value.forEach(col => col.visible = val)
  isIndeterminate.value = false
}

const handleTypeSelect = (type) => {
  currentDataType.value = type
  loadData()
}

const loadData = async () => {
  loading.value = true
  selectedRows.value = []
  searchKeyword.value = ''
  filteredData.value = null
  currentPage.value = 1
  sortState.value = { prop: null, order: null }
  
  try {
    const caseId = route.query.caseId
    if (!caseId) throw new Error('未指定案件ID')
    
    if (window.electronAPI) {
      const response = await window.electronAPI.data.get({ caseId, dataType: currentDataType.value, pageSize: 5000 }) 
      
      const rawData = response.data || []
      
      allData.value = rawData.map(row => {
        if (row.extra_data) {
          try {
            const extra = JSON.parse(row.extra_data)
            Object.assign(row, extra)
          } catch (e) {
            console.error('解析 extra_data 失败', e)
          }
        }
        
        if (row.transaction_time) row.transaction_time = formatDate(row.transaction_time)
        if (row.start_time) row.start_time = formatDate(row.start_time)
        if (row.check_in_time) row.check_in_time = formatDate(row.check_in_time)
        if (row.check_out_time) row.check_out_time = formatDate(row.check_out_time)
        
        return row
      })
      
      initColumns()
      nextTick(() => {
        initSortable()
      })
    }
  } catch (error) {
    console.error('加载数据失败', error)
    ElMessage.error('加载数据失败: ' + error.message)
    allData.value = []
  } finally {
    loading.value = false
  }
}

const performSearch = () => {
  if (!searchKeyword.value.trim()) {
    filteredData.value = null
    currentPage.value = 1
    return
  }
  
  const keywords = searchKeyword.value.toLowerCase().split(/\s+/).filter(k => k)
  filteredData.value = allData.value.filter(row => {
    const rowStr = Object.values(row).join(' ').toLowerCase()
    return keywords.every(k => rowStr.includes(k))
  })
  currentPage.value = 1
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSortChange = ({ prop, order }) => {
  sortState.value = { prop, order }
}

const handlePageSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handlePageChange = (val) => {
  currentPage.value = val
}

const handleDeleteData = async () => {
  if (selectedRows.value.length === 0) return ElMessage.warning('请先选择要删除的数据')
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条数据吗？此操作不可恢复。`,
      '警告',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    
    const caseId = route.query.caseId
    if (window.electronAPI) {
      const res = await window.electronAPI.data.delete({
        caseId,
        dataType: currentDataType.value,
        ids: selectedRows.value.map(r => r.id)
      })
      
      if (res.success) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error('删除失败: ' + res.message)
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作出错: ' + error.message)
    }
  }
}

const handleClearData = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要清空所有【${dataTypes[currentDataType.value]}】数据吗？此操作不可恢复！`,
      '严重警告',
      { confirmButtonText: '确定清空', cancelButtonText: '取消', type: 'error' }
    )
    
    const caseId = route.query.caseId
    if (window.electronAPI) {
      const res = await window.electronAPI.data.clear({
        caseId,
        dataType: currentDataType.value
      })
      
      if (res.success) {
        ElMessage.success('清空成功')
        loadData()
      } else {
        ElMessage.error('清空失败: ' + res.message)
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作出错: ' + error.message)
    }
  }
}

const exportCurrentData = async () => {
  if (currentData.value.length === 0) return ElMessage.warning('当前没有数据可导出')
  
  try {
    const filePath = await window.electronAPI.file.selectSaveFile({
      title: '导出数据',
      defaultPath: `${dataTypes[currentDataType.value]}_${new Date().toISOString().slice(0, 10)}.xlsx`,
      filters: [{ name: 'Excel 文件', extensions: ['xlsx'] }]
    })
    
    if (!filePath) return
    
    const exportData = currentData.value.map(row => {
      const newRow = {}
      visibleColumns.value.forEach(col => {
        newRow[col.label] = row[col.key]
      })
      return newRow
    })
    
    const res = await window.electronAPI.data.export({
      data: exportData,
      filePath,
      dataType: dataTypes[currentDataType.value]
    })
    
    if (res.success) {
      ElMessage.success(`导出成功！\n文件已保存到：${filePath}`)
    } else {
      ElMessage.error('导出失败: ' + res.message)
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('导出失败: ' + error.message)
  }
}

// Watchers
watch(columnConfig, (newVal) => {
  const checkedCount = newVal.filter(c => c.visible).length
  checkAll.value = checkedCount === newVal.length && newVal.length > 0
  isIndeterminate.value = checkedCount > 0 && checkedCount < newVal.length
  saveColumnConfig()
}, { deep: true })

onMounted(() => {
  loadData()
})

onUnmounted(() => {
  if (sortableInstance) sortableInstance.destroy()
})
</script>

<style scoped>
.data-warehouse-container {
  display: flex;
  height: 100%;
  background: #f5f7fa;
}

.data-main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  padding: 16px;
  overflow: hidden;
}

.data-toolbar {
  padding-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.toolbar-actions {
  display: flex;
  gap: 10px;
}

.data-table-wrapper {
  flex: 1;
  overflow: hidden;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.data-footer {
  padding-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 修改点：列设置下拉菜单样式 */
.column-settings-container {
  padding: 0;
}

.column-settings-header {
  padding: 0 0 8px 0;
  margin-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.column-settings-list {
  max-height: 300px;
  overflow-y: auto;
}

.column-setting-item {
  display: flex;
  align-items: center;
  padding: 4px 0;
}

.column-setting-item:hover {
  background-color: #f5f7fa;
}
</style>